package com.bilibili.lzx.service;

import com.bilibili.lzx.dao.FileDao;
import com.bilibili.lzx.dao.domain.File;
import com.bilibili.lzx.dao.domain.exception.ConditionException;
import com.bilibili.lzx.service.util.FastDFSUtil;
import com.bilibili.lzx.service.util.MD5Util;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class FileService {
    @Resource
    private FastDFSUtil fastDFSUtil;

    @Resource
    private FileDao fileDao;

    public String uploadFileBySlices(MultipartFile slicesFile, @RequestParam String fileMd5, Integer sliceNo, Integer totalSliceNo) throws Exception {
        if(sliceNo==1) {
            File file = fileDao.getFileByMd5(fileMd5);
            if (file != null) {
                return file.getUrl();
            }
        }
        String fileUrl = fastDFSUtil.uploadFileBySlices(slicesFile, fileMd5, sliceNo, totalSliceNo);
        if (StringUtils.isNullOrEmpty(fileUrl)) {
            File file = new File();
            file.setUrl(fileUrl);
            file.setMd5(fileMd5);
            file.setCreateTime(new Date());
            file.setType("");
            fileDao.addFile(file);
        }
        return fileUrl;
    }

    public String fileSlices(MultipartFile file) throws Exception {
        fastDFSUtil.convertFileToSlices(file);
        return "分片成功！";
    }

    public String getFileMd5(MultipartFile file) throws Exception {
        if (file==null){
            throw new ConditionException("获取失败");
        }
        return MD5Util.getFileMD5(file);
    }
}
